// ===============================================
// app_service
//
// Create by will on 2021/11/10 10:29
// Copyright @polynesia.All rights reserved.
// ===============================================

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../generated/l10n.dart';
import '../preference/app_preferences.dart';
import '../preference/app_user_preferences.dart';

class AppService extends GetxService {
  static AppService get to => Get.find();

  final Rx<AppPreferences> appPreferences = AppPreferences().obs;

  /// 主题模式
  final Rx<int> themeMode = 0.obs;

  /// 多主题模式
  final RxString multipleThemesMode = 'default'.obs;

  /// 语言
  Locale? locale;

  final RxString _languageCode = 'zh'.obs;
  final RxString _countryCode = 'CN'.obs;

  //用户最后最后登录时间
  final Rx<DateTime> lastLogin = DateTime.now().obs;

  @override
  void onInit() {
    super.onInit();
    _loadLocalDate();

    //监听 appPreferences 的变化
    ever(appPreferences, handleAppPreferencesChanged);
  }

  Future<void> handleAppPreferencesChanged(AppPreferences preferences) async {
    //监听用户修改的 设置问题
  }

  Future<void> _loadLocalDate() async {
    // 读取用户配置 方便写入内存 到时候 可以相应配读取用户信息
    final preferences = (await AppUserPreferences.getInstance()).app;
    //主题
    themeMode.value =
        preferences.themeMode == null ? 0 : preferences.themeMode!.index;
    multipleThemesMode.value = preferences.multipleThemesMode ?? 'default';

    // /// 这里默认使用系统语言
    // final Locale language = Localizations.localeOf(AppGlobal.context!);
    // locale.value = language;

    if (preferences.languageCode != null && preferences.countryCode != null) {
      _languageCode.value = preferences.languageCode!;
      _countryCode.value = preferences.countryCode!;
      locale = Locale(_languageCode.value, _countryCode.value);
      await Get.updateLocale(locale!);
      await AppIntl.load(locale!);
    }
    //这里可用可不用
    // else {
    //   _languageCode.value = 'zh';
    //   _countryCode.value = 'CN';
    //   locale = Locale(_languageCode.value, _countryCode.value);
    //   await Get.updateLocale(locale!);
    //   await IntlS.load(locale!);
    // }

    // ///这里使用默认的语言 就是强制使用中文 可以不用设置 他会跟随系统
    // _languageCode.value = preferences.languageCode ?? 'zh';
    // _countryCode.value = preferences.countryCode ?? 'CN';
    // locale = Locale(_languageCode.value, _countryCode.value);
    // //这里使用默认的语言 就是强制使用中文 可以不用设置 他会跟随系统

    lastLogin.value = preferences.lastLogin ?? DateTime.now();

    appPreferences.value = preferences;
  }

  Future<void> updateAppPreferences(
      {required AppPreferences preferences}) async {
    appPreferences.value = preferences;
    //保存新的数据
    await AppUserPreferences.getInstance().then((v) => v.setApp(preferences));
  }

  /// 设置-主题模式
  void changeTheme(ThemeMode mode) {
    ///利用get改变主题
    Get.changeThemeMode(mode);

    ///保存主题
    themeMode.value = mode.index;
    final preferences = AppPreferences(
      themeMode: mode,
      multipleThemesMode: multipleThemesMode.value,
      languageCode: _languageCode.value,
      countryCode: _countryCode.value,
    );
    updateAppPreferences(preferences: preferences);
  }

  /// 设置-多主题模式
  void setMultipleThemesMode(String themesMode) {
    multipleThemesMode.value = themesMode;
    final preferences = AppPreferences(
      themeMode: ThemeMode.values[themeMode.value],
      multipleThemesMode: multipleThemesMode.value,
      languageCode: _languageCode.value,
      countryCode: _countryCode.value,
    );
    updateAppPreferences(preferences: preferences);
  }

  /// 设置-语言跟随系统
  void setLocaleSystem() {
    locale = Get.locale = null;
    Get.forceAppUpdate();
    final preferences = AppPreferences(
      themeMode: appPreferences.value.themeMode,
      multipleThemesMode: multipleThemesMode.value,
    );

    updateAppPreferences(preferences: preferences);
  }

  /// 设置-语言
  void setLocale({
    required String languageCode,
    required String countryCode,
  }) {
    _languageCode.value = languageCode;
    _countryCode.value = countryCode;
    final language = Locale(languageCode, countryCode);
    locale = language;

    Get.updateLocale(language);
    AppIntl.load(language);

    final preferences = AppPreferences(
      themeMode: appPreferences.value.themeMode,
      multipleThemesMode: multipleThemesMode.value,
      languageCode: _languageCode.value,
      countryCode: _countryCode.value,
    );
    updateAppPreferences(preferences: preferences);
  }

  // ///app更新升级
  // Future<void> checkAppUpgrade() async {
  //   if (configEntity.value.anActionType.toString() != '6') {
  //     return;
  //   }
  //   if (configEntity.value.isEmpty()) {
  //     return;
  //   }
  //   final targetVersion = configEntity.value.version.toString();
  //   final isUp =
  //       await AppUpgrade.checkUpdateVersion(targetVersion: targetVersion);
  //   if (isUp) {
  //     AppUpgrade.appUpgrade(
  //         Get.context!,
  //         _checkAppInfo(
  //           appConfigs: configEntity.value,
  //         ),
  //         cancelText: '以后再说',
  //         okText: '马上升级',
  //         okBgColor: AppStyle.primaryColor,
  //         iosAppId: 'id88888888', onCancel: () {
  //       debugPrint('onCancel');
  //     }, onOk: () {
  //       debugPrint('onOk');
  //     }, downloadProgress: (count, total) {
  //       debugPrint('count:$count,total:$total');
  //     }, downloadStatusChange: (status, {dynamic error}) {
  //       debugPrint('status:$status,error:$error');
  //     }, progressBarColor: AppStyle.primaryColor.withOpacity(0.4));
  //   }
  // }
  //
  // //app更新
  // Future<AppUpgradeInfo> _checkAppInfo(
  //     {required ConfigEntity appConfigs}) async {
  //   var announcement = appConfigs.announcement!.toString();
  //   if (announcement.contains('<br />\n')) {
  //     announcement = announcement.replaceAll('<br />\n', ';');
  //   }
  //   announcement = announcement.replaceAll('${appConfigs.version}升级：\n', '');
  //   final contents = announcement.split(';');
  //   final apkUrl = appConfigs.apk_url;
  //
  //   //注意下载链接
  //   return AppUpgradeInfo(
  //     title: '新版本升级',
  //     contents: contents,
  //     apkDownloadUrl: apkUrl,
  //   );
  // }
}
